package com.tobeing.picture.picker.adapters;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.tobeing.picture.picker.R;
import com.tobeing.picture.picker.customs.ImageLoader;
import com.tobeing.picture.picker.customs.QueneType;
import com.tobeing.picture.picker.models.Image;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.security.auth.login.LoginException;

/**
 * Created by Administrator on 2017/11/16/016.
 */

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private List<String> mImages;
    private Map<Integer, View> mViews;
    private Set<String> mSelectedImage;

    public ImageAdapter(Context context, List<String> images) {
        mContext = context;
        mImages = images;
        mViews = new HashMap<>();
        mSelectedImage = new HashSet<>();
    }

    @Override
    public int getCount() {
        return mImages == null ? 0 : mImages.size();
    }

    @Override
    public String getItem(int position) {
        return mImages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (!mViews.containsKey(position) || mViews.get(position) == null) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.image_item, null, false);
            mViews.put(position, view);
            final ImageView ivImage = view.findViewById(R.id.iv_image);
            final ImageView ivSelect = view.findViewById(R.id.iv_select);
            ivImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mSelectedImage.contains(mImages.get(position))){
                        mSelectedImage.remove(mImages.get(position));
                        ivSelect.setImageResource(R.mipmap.image_unselected);
                    }else {
                        mSelectedImage.add(mImages.get(position));
                        ivSelect.setImageResource(R.mipmap.image_selected);
                    }
                }
            });

            ImageLoader.getInstance(mContext, 3, QueneType.LIFO).setSize(parent.getWidth() / 3, parent.getWidth() / 3);
            ImageLoader.getInstance(mContext, 3, QueneType.LIFO).loadImage(mImages.get(position), ivImage);
        }
        return mViews.get(position);
    }
}
